package com.es.demo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author zqf
 * @Date 2022/10/13 11:51
 * @Description: 创建索引
 */
@RestController("/index")
@Api (tags = "创建索引")
public class CreatedIndexController {

    @Resource
    private RestHighLevelClient restHighLevelClient;


    @GetMapping("/create")
    @ApiOperation("创建索引")
    private String createdIndex(@RequestParam("index")@ApiParam("需要创建的索引名") String index) throws IOException {
        //发起创建索引请求
        CreateIndexRequest request = new CreateIndexRequest(index);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);

        //获取创建结果
        boolean isSuccess = createIndexResponse.isAcknowledged();
        if (isSuccess) {
            return "创建成功";
        }
        return "创建失败";
    }



    @GetMapping("/exits")
    @ApiOperation( "索引是否存在")
    private String exitsIndex(@RequestParam("index")@ApiParam("需要查询的索引名") String index) throws IOException {
        GetIndexRequest request = new GetIndexRequest(index);
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        if (exists) {
            return "索引存在";
        }
        return "索引不存在";
    }



    @GetMapping("/delete")
    @ApiOperation("索引删除")
    public String testDeleteIndex(@RequestParam("index")@ApiParam("需要删除的索引名") String index) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(index);
        AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        if (response.isAcknowledged()) {
            return "索引删除成功";
        }
        return "索引删除失败";
    }

}
